package com.shop.user.api.controller;

import com.shop.common.entity.user.UserBase;
import com.shop.common.model.ServiceBean;
import com.shop.common.tmpl.BaseController;
import com.shop.common.util.RedisUtil;
import com.shop.common.util.SendCodeUtil;
import com.shop.common.util.SessionUtils;
import com.shop.common.util.state.KeyPrefix;
import com.shop.common.util.state.ResultCode;
import com.shop.user.api.model.UserBaseModel;
import com.shop.user.atom.atomsvc.impl.UserAtomSvc;
import com.shop.user.conf.util.emiltool.EmailService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user/reg/")
@CrossOrigin
public class UserRegController extends BaseController {
    static final String GET_VERCODE_TIME = "verCodeTime_";
    static final String VERCODE = "verCode_";
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    EmailService emailService;
    @Autowired
    UserAtomSvc userService;
    @Autowired
    SessionUtils sessionUtils;

    /**
     * @Author zhoulk
     * @Description // 获取验证码
     * @Date 13:22 2018/11/29
     *
     * @Param [account, regType]
     * @return com.shop.user.api.model.ResponseModel
     * @errorCode // 500:参数错误 400:操作频繁 401:账号已注册 402:验证码发送失败
     **/
    @GetMapping("getVerCode")
    public String getVerifily(String account, Integer regType) {
        if (account == null || "".equals(account) || regType == null || regType > 1 || regType < 0) {
            return returnFailed("参数错误");
        }
        String key = GET_VERCODE_TIME + account;
        Boolean isHis = redisUtil.exists(key);
        if (isHis) {
            Long hisTime = (Long) redisUtil.getObject(key);
            Map<String, Object> rData = new HashMap<>();
            rData.put("hisTime", hisTime);
            return returnJSON(ResultCode.FAILED.value(), "请不要频繁操作", rData);
        }
        Boolean accountIsUsed = userService.accountUse(account);
        if (accountIsUsed) {
            return returnFailed("账号已注册");
        }
        if (!"".equals(account) && regType == 1) {
            Long nowTime = System.currentTimeMillis();
            redisUtil.set(key, nowTime, 59);
            int code = new Random().nextInt(8000) + 1234;//生成一个随机码
            key = VERCODE + account;
            redisUtil.set(key, code, 60 * 30);
            Map<String, Object> map = new HashMap<>();
            map.put("time", new Date());
            map.put("message", code);
            map.put("toUserName", account);
            String statue = emailService.sendHtmlMail(account, "注册：验证码", map, "model.ftl");
            if ("F".equals(statue)) {
                redisUtil.del(key);
                return returnFailed("验证码发送失败!!!请检查邮箱是否正确");
            }
        } else if (regType == 0) {
            ServiceBean serviceBean = SendCodeUtil.SEND_BY_PHONE(KeyPrefix.REG, account);
            if (serviceBean.isSuccess()) {
                return returnSuccess("验证码已发送，请注意查收!!!");
            } else {
                return returnSvc(serviceBean);
            }
        }
        return returnSuccess("验证码已发送，请注意查收!!!");
    }

    /**
     * @Author zhoulk
     * @Description //用户注册
     * @Date 13:24 2018/11/29
     *
     * @Param [userModel]
     * @return com.shop.user.api.model.ResponseModel
     * @errorCode //TODO
     **/
    @PostMapping("addUsers")
    public String addUsers(@RequestBody UserBaseModel userModel, HttpServletRequest request) {
        String account = userModel.getAccount();
        String password = userModel.getPassword();
        Integer regType = userModel.getRegType();
        String verCode = userModel.getVerCode();
        password = DigestUtils.md5Hex(password);
        //参数校验
        boolean flag = SendCodeUtil.VALIDATE_CODE(KeyPrefix.REG, userModel.getAccount(), verCode);
        if (!flag) {
            return returnFailed("验证码错误或已过期，请重新获取验证码!!!");
        }
        Boolean accountIsUsed = userService.accountUse(userModel.getAccount());
        if (accountIsUsed) {
            return returnFailed("账号已注册");
        }

        UserBase userBase = new UserBase();
        userBase.setAccount(account);
        userBase.setPassword(password);
        if (regType == 0) {
            userBase.setPhone(account);
        } else {
            userBase.setEmail(account);
        }
        userBase.setType(regType);
        userBase.setSchoolId(userModel.getSchoolId());
        userBase.setSchoolName(userModel.getSchoolName());
        //调用service方法
        ServiceBean<Integer> regResult = userService.addUser(userBase);
        if (!regResult.isSuccess()) {
            return returnFailed(regResult.getMsg());
        }
        Map<String, String> resultMap = new HashMap<>();
        HttpSession session = request.getSession();
        String token = session.getId();
        resultMap.put("AUTHTOKEN", token);
        resultMap.put("NICKNAME", userBase.getNickname() + "");
        resultMap.put("STATUS", userBase.getStatus() + "");
        sessionUtils.SET_USER(userBase, token);
        return returnData(resultMap);
    }


}
